import type {MorghulisChannel, MorghulisChannels, MorghulisSockets} from "../types/tool/channel.types";
import {useMorghulisAuthorize} from "./authorize";
import {inject, reactive, ref, watch} from "vue";
import {useWebSocket} from "@vueuse/core";

export function useMorghulisSockets() {
    const {open, status} = inject('sockets') as MorghulisSockets
    return {open, status}
}

export function loadMorghulisSockets(baseURL: string): MorghulisSockets {
    const {$client} = useMorghulisAuthorize()
    const channels = reactive<MorghulisChannels>({})
    const URL = `${baseURL}${$client}/`
    let status = ref('DISCONNECTED')
    const {data, open} = useWebSocket(URL, {
        onDisconnected: () => status.value = 'CONNECTING',
        onConnected: () => status.value = 'CONNECTED',
        autoReconnect: {
            retries: 10, delay: 1000,
            onFailed: () => status.value = 'DISCONNECTED',
        }
    })
    watch(data, () => {
        let {payload, handler, status} = JSON.parse(data.value)
        const channel: MorghulisChannel = channels[handler]
        const fun = channel[status as 'start' | 'stop' | 'proceed']
        fun && fun(payload)
    }, {deep: true})

    return {
        open,
        status,
        channels
    }
}